package com.hundsun.cprs.yyt.service.dilivery.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.inst2xsd.RussianDollStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.exception.ServiceException;
import com.hundsun.cprs.yyt.service.dilivery.dao.DeliveryLogDao;
import com.hundsun.cprs.yyt.service.dilivery.domain.Delivery;
import com.hundsun.cprs.yyt.service.dilivery.domain.DeliveryCompany;
import com.hundsun.cprs.yyt.service.dilivery.domain.DeliveryLog;
import com.hundsun.cprs.yyt.service.dilivery.domain.query.DeliveryLogQuery;
import com.hundsun.cprs.yyt.service.dilivery.dto.DeliveryLogInfo;
import com.hundsun.cprs.yyt.service.dilivery.enums.EnumDiliveryType;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryCompanyService;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryLogService;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryService;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.util.BeanUtils;

@Service
public class DeliveryLogServiceImpl extends BaseService implements DeliveryLogService {
    
    @Autowired
    private DeliveryLogDao logDao;
    
    @Autowired
    private DeliveryCompanyService deliveryCompanyService;
    
    @Autowired
    private DeliveryService deliveryService;
    
    @Autowired
    @Qualifier("commonThreadPool")
    private Executor executor;
    
    @Override
    @Transactional
    public void batchInsert(List<DeliveryLog> logs) {
        Assert.notEmpty(logs, "参数必填");
        
        for(DeliveryLog log : logs){
            log.setStatus(0);
        }
        logDao.insertBatch(logs);
    }

    @Override
    public void queryByPage(DeliveryLogQuery query) {
       List<DeliveryLogInfo> result = logDao.queryByConditon(query);
       query.compatible(result);
    }

    @Override
    public void handleBatchDelivery() {
        //异步处理导入记录
        executor.execute(new Runnable() {
            public void run() {
                //查询所有物流公司信息
                final Map<String,DeliveryCompany> companys = loadCompanyInfo();
                
                while(true){
                    final DeliveryLogQuery query = new DeliveryLogQuery();
                    query.setStatus(0);
                    query.setPageSize(200);
                    query.setPageNo(1);
                    queryByPage(query);
                    
                    if (query.getTotalCount() == 0) {
                        break;
                    }
                    //更新该批数据未处理中
                    logDao.updateStatusByBatch(query.getData(), 1);
                    
                    executor.execute(new Runnable() {
                        public void run() {
                            doHandleBatchDelivery(query.getData(),companys);
                        }
                    });
                }
            }
        });       
    }
    
    protected void doHandleBatchDelivery(List<DeliveryLogInfo> deliveryLog,Map<String,DeliveryCompany> companys){
        List<DeliveryLogInfo> result = deliveryLog;
        for(DeliveryLogInfo data : result){
            try {
                if (data.getOrderId() == null) {
                    // 订单不存在
                    data.setStatus(-1);
                    data.setRemark("订单编号不存在");
                    logDao.updateByPrimaryKey(data);
                    continue;
                }
                
                if (EnumsOrderStatus.WAIT_DELIVERY.getStatus() != data.getOrderStatus()) {
                    data.setStatus(-1);
                    data.setRemark("订单不是发货订单");
                    logDao.updateByPrimaryKey(data);
                    continue;
                }
                
                if (EnumDiliveryType.ENTRUST.getValue().equals(data.getDeliveryType())) {
                    data.setStatus(-1);
                    data.setRemark("订单不允许发货");
                    logDao.updateByPrimaryKey(data);
                    continue;
                }
                
                Delivery delivery = null;
                
                // 物流单，校验物流公司是否准确
                if (EnumDiliveryType.DELIVERY.getValue().equals(data.getDeliveryType().toString())) {
                    if (StringUtils.isEmpty(data.getBatchNumber()) || StringUtils.isEmpty(data.getLogisticsCompany())) {
                        // 物流单 物流信息必填
                        data.setStatus(-1);
                        data.setRemark("物流信息必填");
                        logDao.updateByPrimaryKey(data);
                        continue;
                    }
                    
                    if (companys == null || companys.isEmpty() || !companys.containsKey(data.getLogisticsCompany())) {
                        //系统不支持的物流公司
                        data.setStatus(-1);
                        data.setRemark("系统不支持的物流公司");
                        logDao.updateByPrimaryKey(data);
                        continue;
                    }
                    
                    delivery = new Delivery();
                    delivery.setAddress(data.getAddress());
                    delivery.setContactNumber(data.getPhone());
                    delivery.setUserName(data.getConsignee());
                    delivery.setBatchNumber(data.getBatchNumber());
                    delivery.setCompanyCode(companys.get(data.getLogisticsCompany()).getCompanyCode());
                    delivery.setLogisticsCompany(companys.get(data.getLogisticsCompany()).getLogisticsCompany());
                    delivery.setOrderId(data.getOrderId());
                    
                }
                
                if (EnumDiliveryType.SELFTGET.getValue().equals(data.getDeliveryType().toString())) {
                    delivery = new Delivery();
                    delivery.setAddress(data.getAddress());
                    delivery.setContactNumber(data.getPhone());
                    delivery.setUserName(data.getConsignee());
                    delivery.setCompanyCode(BigDecimal.ZERO.toString());
                    delivery.setOrderId(data.getOrderId());
                }
            
                if (delivery != null) {
                    deliveryService.createDelivery(delivery);
                }
                data.setStatus(2);
                data.setRemark("成功");
                logDao.updateByPrimaryKey(data);
            } catch (ServiceException e) {
                data.setStatus(-1);
                data.setRemark(e.getMessage());
                logDao.updateByPrimaryKey(data);
            } catch (Exception e) {
                data.setStatus(-1);
                data.setRemark("处理异常");
                logDao.updateByPrimaryKey(data);
                logger.error("导入处理异常", e);
            }
        }
        
    }
    
    private Map<String,DeliveryCompany> loadCompanyInfo(){
        List<DeliveryCompany>  companys = deliveryCompanyService.queryCompanyList();
        if (companys != null) {
            return BeanUtils.mapByKey("logisticsCompany", companys);
        }
        return null;
    }

    @Override
    public void deleteAll() {
        logDao.deleleAll();
    }

}
